package com.luckberry.murder.controller.api;

import com.alibaba.fastjson.JSON;
import com.luckberry.murder.controller.auth.AuthController;
import com.luckberry.murder.entity.User;
import com.luckberry.murder.service.UserService;
import com.luckberry.murder.util.JSONUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/api")
public class ApiUserController {

    @Resource
    private UserService service;

    @ResponseBody
    @RequestMapping(value = "/onlines", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public String getOnlines() {
        return JSON.toJSONString(AuthController.onlines.values());
    }

    @ResponseBody
    @RequestMapping(value = "/users", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public String getUsers() {
        return JSON.toJSONString(service.getUsers());
    }

    @ResponseBody
    @RequestMapping(value = "/user/{uid}", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public String getUser(@PathVariable("uid") int uid) {
        return JSON.toJSONString(service.getUser(uid));
    }

    @ResponseBody
    @RequestMapping(value = "/user/account", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.GET)
    public String getUserByAccount(String key) {
        return JSON.toJSONString(service.getUserByAccount(key));
    }

    @ResponseBody
    @RequestMapping(value = "/user", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.POST)
    public String addUser(@RequestBody String json) {
        return JSONUtil.result(service.addUser(JSON.parseObject(json, User.class)));
    }

    @ResponseBody
    @RequestMapping(value = "/user/{uid}", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable("uid") int uid) {
        return JSONUtil.result(service.deleteUser(uid));
    }

    @ResponseBody
    @RequestMapping(value = "/user", produces = {"application/json;charset=UTF-8"}, method = RequestMethod.PUT)
    public String editUser(HttpSession session, @RequestBody String json) {
        boolean result = service.editUser(JSON.parseObject(json, User.class));

        User user = (User) session.getAttribute("user");
        session.setAttribute("user", service.getUser(user.getUid()));

        return JSONUtil.result(result);
    }
}
